// Product detail page
// ===================

define(['require', 'zepto', 'wx', 'wxpay', 'utils', 'page/protocol', 'wxshare', 'smExtend', 'smCityPicker'], 
        function(require, $, wx, wxpay, utils, protocol, wxshare) {
  return {
    init: function(data) {
      this.amount = data.amount;
      this.type = data.type;
      $("#city-picker").cityPicker({
        toolbarTemplate: '<header class="bar bar-nav">\
        <button class="button button-link pull-right close-picker">确定</button>\
        <h1 class="title">选择省市区</h1>\
        </header>'
      });
      
      $(document).on('click','.add-new', function () {
        $.closeModal('.list-popup');
        $.popup('.select-popup');
      });
      
      // forbidden wx share
      //wxshare.initShare(data.jsConfig, false)
      if(data.jsConfig) {
        wx.config({
          appId: data.jsConfig.appid,
          timestamp: data.jsConfig.timestamp,
          nonceStr: data.jsConfig.nonceStr,
          signature: data.jsConfig.signature,
          jsApiList: ['hideMenuItems','checkJsApi','openAddress']
        })
        
        wxshare.initShare(data.jsConfig, true, {
          name: "人马君乐在美味即食魔芋拌面",
          desc: "人马君 乐在美味即食魔芋拌面（肽+） 轻卡低热量 减脂餐 魔芋面主食品方便即食速食",
          link: "http://weixin.fit-start.co/moyu",
          cover: "https://prod.qiniu.fit-start.edoomath.com/moyu-logo.png"
        })
        
        wx.ready(function() {
          wx.hideOptionMenu()
        })
        
        $(document).on('click','.wechat-address', function () {
          wx.openAddress({ success: function (res) { 
            
            // 1：关闭弹窗
            $.closeModal('.select-popup');
            
            // 2: 填充hidden
            $('input[name="nameValue"]').val(res.userName)
            var pcd = res.provinceName+ " " + res.cityName
            $('input[name="mobileValue"]').val(res.telNumber)
            $('input[name="pcdValue"]').val(pcd)
            $('input[name="addressValue"]').val(res.detailInfo)
            
            // 3.展示地址
            $(".address-info").find(".user-info").html(res.userName + "（"+res.telNumber+"）")
            $(".address-info").find(".address-detail").html(pcd+" " +res.detailInfo)
            $(".address-info").removeClass("hide")
            $(".empty-address").addClass("hide")
          }, cancel: function (errMsg) {
            
          }
          })
        })
      }
      
      $(document).on('click','.open-select-popup', function () {
        $.popup('.select-popup');
      })
      
      
      $(document).on('click','.add-address', function () {
        var name = $('input[name="name"]').val().trim()
        var mobile = $('input[name="mobile"]').val().trim()
        var pcd = $('input[name="pcd"]').val().trim()
        var address = $('textarea[name="address"]').val().trim()
        if(!name) {
          $.toast("请填写收货人姓名")
          return
        }
        if(!mobile) {
          $.toast("请填写收货人手机")
          return
        }
        if(!pcd) {
          $.toast("请填写省市区")
          return
        }
        if(!address) {
          $.toast("详细地址不能为空")
          return
        }
        
        $.closeModal('.select-popup');
        
        $('input[name="nameValue"]').val(name)
        $('input[name="mobileValue"]').val(mobile)
        $('input[name="pcdValue"]').val(pcd)
        $('input[name="addressValue"]').val(address)
        
        // 3.展示地址
        $(".address-info").find(".user-info").html(name + "（"+mobile+"）")
        $(".address-info").find(".address-detail").html(pcd+" " +address)
        $(".address-info").removeClass("hide")
        $(".empty-address").addClass("hide")
        
      })
      
      this.bindOrderSubmitAction();
    },
    
    // order submit evvent handler
    bindOrderSubmitAction: function() {
      
      var thatSubmit = this
      
      var submitButton = $("a.button-order")
      
      submitButton.on('click', function(e){
        e.preventDefault()
        // init all data
        var data = thatSubmit.onInitData()
        // validate all input
        if(thatSubmit.onValidateData(data)) {
          thatSubmit.onSubmitOrder(data)
        }
      })
      
    },
    
    onSubmitOrder: function(data) {
      var that = this;
      $.showPreloader('正在提交订单')

      var processedData = _.mapObject(data, function(obj) {
        return obj.value
      })
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/moyu/orders',
        data: processedData
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, function(result) {
          $.toast('创建订单成功')
          setTimeout(function() {
// if(result.data.orderType === 'others') {
// window.location.href = __CTX__.root + '/orders/shipping-address?order=' +
// result.data.orderId;
// }else {
// that.formSubmit(window.__CTX__.root + '/pay', {'order': result.data.orderId},
// 'POST').submit();
            that.orderId = result.data.orderId;
            $.toast('支付请求中')
            that.requestWxPay();
// }
          }, 1000)
        }, function(result) {
          $.toast(result.message || '订单创建失败')
        })
      })
    },
    
    /**
     * Request server to prepare WeChat payment data
     */
    requestWxPay: function() {
      $.showPreloader('正在提交支付数据')
      var that = this
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/moyu/wxpay/prepare',
        data: {
          'orderId': this.orderId,
          'currentUrl': location.href.split('#')[0]
        }
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, that.configWxPay.bind(that), function(result) {
          $.toast(result.message || '请求支付数据失败')
        })
      })
    },
    
    /**
     * Handle success WeChat pay, config WeChat JS SDK and invoke pay
     */
    configWxPay: function(result) {
      var that = this
          jsConfig = result.data.jsConfig,
          payConfig = result.data.payConfig

      wxpay.injectConfig(jsConfig, ['chooseWXPay'])
      wxpay.invokePay(payConfig, function(res) {
        $.toast('支付成功，正在为您跳转')
        setTimeout(function() {
          window.location.href = window.__CTX__.root + '/moyu/success?orderId=' + that.orderId
        }, 1000)
      })
    },
    
    formSubmit: function (url, data, method) {
      if (method == null) method = 'POST';
      if (data == null) data = {};

      var form = $('<form>').attr({
          method: method,
          action: url
      }).css({
          display: 'none'
      });

      var addData = function (name, data) {
          if ($.isArray(data)) {
              for (var i = 0; i < data.length; i++) {
                  var value = data[i];
                  addData(name + '[]', value);
              }
          } else if (typeof data === 'object') {
              for (var key in data) {
                  if (data.hasOwnProperty(key)) {
                      addData(name + '[' + key + ']', data[key]);
                  }
              }
          } else if (data != null) {
              form.append($('<input>').attr({
                  type: 'hidden',
                  name: String(name),
                  value: String(data)
              }));
          }
      };

      for (var key in data) {
          if (data.hasOwnProperty(key)) {
              addData(key, data[key]);
          }
      }
      return form.appendTo('body');
  },
    
    // init data
    onInitData: function() {
      var that = this;
      return {
        'amount': {
          'value': that.amount,
          'message': '数量不能为空'
        },
        'type': {
          'value': that.type,
          'message': '口味不能为空'
        },
        'name': {
          'value': $('input[name="nameValue"]').val().trim(),
          'message': '请填写收货人姓名'
        },
        'mobile': {
          'value': $('input[name="mobileValue"]').val().trim(),
          'message': '请填写联系人手机'
        },
        'pcd': {
          'value': $('input[name="pcdValue"]').val().trim(),
          'message': '所在地区不能为空'
        },
        'address': {
          'value': $('input[name="addressValue"]').val().trim(),
          'message': '详细地址不能为空'
        }
      }
    },
    
    onValidateData: function(data) {
      var valid = _.find(data, function(item) {
        return !item.value
      })

      if (!!valid) return $.toast(valid.message)

      if (data.amount.value == 0) {
        return $.toast('请填写正确的数量') 
      }

      return true
    }
    
  }
})